package cnooc.dataAnalysis.service.impl;



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cnooc.common.config.InfluxDbComUtil;
import cnooc.dataAnalysis.domain.HistoryDataCols;
import cnooc.dataAnalysis.service.HistoryService;
import cnooc.energy.domain.DeviceDataLocation;
import cnooc.energy.domain.Equipment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 历史数据查询Service业务层处理
 *
 * @author 韩是非
 * @date 2023-11-28
 */
@Service
@Slf4j
public class HistoryServiceImpl implements HistoryService {


    @Resource
    InfluxDbComUtil influxDbComUtil;

    private static final String QUERY_HISTORICAL_DATA_MULT_LOCATION = "select {}  from  {}  where time >'{}' and time <'{}' fill(0) limit {} offset {} tz('Asia/Shanghai') ";
    private static final String QUERY_HISTORICAL_DATA_COUNT = "select count({})  from  {}  where time >'{}' and time <'{}'  tz('Asia/Shanghai') ";

    @Override
    public Long count(String tableName, String locate, List<String> dateTimeRange) {
        DateTime beginDateTime = DateUtil.parse(dateTimeRange.get(0), "yyyy-MM-dd HH:mm:ss");
        DateTime endDateTime = DateUtil.parse(dateTimeRange.get(1), "yyyy-MM-dd HH:mm:ss");
        String queryStr = StrUtil.format(QUERY_HISTORICAL_DATA_COUNT, locate, tableName, beginDateTime, endDateTime);
        return Long.parseLong(NumberUtil.toStr(new BigDecimal(ObjectUtil.isEmpty(influxDbComUtil.query(queryStr))?"0":influxDbComUtil.query(queryStr).get(0).get("count").toString())));
    }


    @Override
    public List<Map<String, Object>> queryHistoricalData(List<String> dateTimeRange, Equipment equipment, List<DeviceDataLocation> ddlList, int limit, int offset) {
        DateTime beginDateTime = DateUtil.parse(dateTimeRange.get(0), "yyyy-MM-dd HH:mm:ss");
        DateTime endDateTime = DateUtil.parse(dateTimeRange.get(1), "yyyy-MM-dd HH:mm:ss");
        List<String> locates = ddlList.stream().map(DeviceDataLocation::getLocation).collect(Collectors.toList());
        String queryStr = StrUtil.format(QUERY_HISTORICAL_DATA_MULT_LOCATION, CollUtil.join(locates, ","), equipment.getTableName(), beginDateTime, endDateTime, limit, offset);
        return influxDbComUtil.query(queryStr);
    }



    @Override
    public Map<String, Object> resultPackaging(Equipment equipment, List<DeviceDataLocation> deviceDataLocation, List<?> maps) {
        Map<String, Object> result = new HashMap<>();
        List<HistoryDataCols> cols = colsPacking();
        List<Map<String, String>> rows = new ArrayList<>();

        for (DeviceDataLocation dataLocation : deviceDataLocation) {
            cols.add(new HistoryDataCols(dataLocation.getLocation().toLowerCase(), dataLocation.getName()));
        }
        for (Object map : maps) {
            Map map1 = (Map) map;
            Map<String, String> row = new HashMap<>();
            row.put("name", equipment.getName());
            for (Object key : map1.keySet()) {
                row.put(key.toString(), map1.get(key).toString());
            }
            String time = map1.get("time").toString();
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(time, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String format = zonedDateTime.format(targetFormatter);
            row.put("time", format);
            rows.add(row);
        }
        result.put("cols", cols);
        result.put("rows", rows);
        return result;
    }


    public List<HistoryDataCols> colsPacking() {
        return CollUtil.newArrayList(new HistoryDataCols("name", "设备名称", false,"150px"), new HistoryDataCols("time", "时间", false,"230px"));
    }

}
